package edu.hnu.tradeserver.controller;

import edu.hnu.commonutils.EnumResultCode;
import edu.hnu.commonutils.Result;
import edu.hnu.commonutils.UserDb.TradersResponse;
import edu.hnu.commonutils.model.User;
import edu.hnu.tradeserver.auth.JwtOperator;
import edu.hnu.tradeserver.entity.Test;
import edu.hnu.tradeserver.entity.Trades;
import edu.hnu.tradeserver.feign.UserFeign;
import edu.hnu.tradeserver.service.TestService;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;

/**
 * @author 21g
 * @version 1.0
 * @className TestController
 * @since 1.0
 */
@RestController
//@CrossOrigin(origins = "*")
@Api(value = "测试接口",tags = {"test"})
public class TestController {

    @Autowired
    TestService testService;
    @Autowired
    JwtOperator jwtOperator;

    private User parseToken(String token){
        Claims claims = jwtOperator.getClaimsFromToken(token);
        User user = new User(-1L,-2,false);
        try {
            Long id = Long.parseLong(claims.get("id").toString());
            int userType= Integer.parseInt(claims.get("user_type").toString());
            if (userType != 1) {
                //判断是不是trader
                user.setAuthorized(false);
            }else {
                user.setUserType(userType);
                user.setId(id);
                user.setAuthorized(true);
            }
        } catch (NumberFormatException e) {
            user.setAuthorized(false);
            return user;
        }
        return user;
    }

    @PostMapping("/testAddRecord")
    public Result testAddRecord(String client_name, String ticker, String ric, String size, BigDecimal price , BigDecimal currency,
                                String issuer_sector, String salesperson, String ht_pt){
        Test test = new Test();
        test.setHt_pt(ht_pt);
        test.setRic(ric);
        test.setCurrency(currency);
        test.setPrice(price);
        test.setSalesperson(salesperson);
        test.setSize(size);
        test.setClientName(client_name);
        test.setIssuerSector(issuer_sector);
        test.setTicker(ticker);
        return testService.addTradeRecord(test);
    }


    @GetMapping("/stocksInfo")
    public Result stocksInfo(){
        return testService.stocksInfo();
    }

    @PostMapping("/testToken")
    public Result testToken(@RequestHeader("token") String token) {
        User user = parseToken(token);
        if(!user.isAuthorized()){
            return Result.error(EnumResultCode.UNAUTHORIZED);
        }

        System.out.println(user.getUserType());
        System.out.println(user.getId());
        return Result.ok(user,"good");
    }

}
